package oa.hleast.xswl.service.questionnaire.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.druid.sql.visitor.functions.Char;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import oa.hleast.common.web.util.RequestUtils;
import oa.hleast.xswl.mapper.questionnaire.QmsAnswerMapper;
import oa.hleast.xswl.mapper.questionnaire.QmsProblemMapper;
import oa.hleast.xswl.pojo.domain.UmsMember;
import oa.hleast.xswl.pojo.domain.questionnaire.*;
import oa.hleast.xswl.pojo.form.questionnaire.UserAnswerForm;
import oa.hleast.xswl.pojo.form.questionnaire.UserQuestionnaireForm;
import oa.hleast.xswl.pojo.vo.ShowQuestionnaireVo;
import oa.hleast.xswl.pojo.vo.questionnaire.*;
import oa.hleast.xswl.service.ISysCommonConfigService;
import oa.hleast.xswl.service.IUmsUserService;
import oa.hleast.xswl.service.questionnaire.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: 302
 * @date: 2021-07-19 18:44:56
 * @description: 用户问卷管理接口实现
 */
@Slf4j
@Transactional
@Service("UserQuestionnaireService")
@AllArgsConstructor
public class UserQuestionnaireServiceImpl implements UserQuestionnaireService {

    private final QmsUserAnswerService qmsUserAnswerService;

    private final QmsUserQuestionnaireService qmsUserQuestionnaireService;

    private final QmsUserProblemService qmsUserProblemService;

    private final ISysCommonConfigService commonConfigService;

    private final QmsAnswerService qmsAnswerService;

    private final QmsQuestionnaireService qmsQuestionnaireService;

    private final QmsProblemService qmsProblemService;

    @Autowired
    private QmsUserQuestionnaireStateService qmsUserQuestionnaireStateService;

    @Autowired
    private IUmsUserService iUmsUserService;

    @Override
    public UserQuestionnaireResultVo getUserQuestionnaireResult(Long userId) {

        UserQuestionnaireResultVo userQuestionnaireResultVo = new UserQuestionnaireResultVo();
        /**
         * 用户问卷数据
         */
        QmsUserQuestionnaire questionnaire = qmsUserQuestionnaireService.getOne(new LambdaQueryWrapper<QmsUserQuestionnaire>().eq(QmsUserQuestionnaire::getUserId, userId));
        // 试题数据
        List<QmsUserProblem> list = qmsUserProblemService.list(new LambdaQueryWrapper<QmsUserProblem>()
                .eq(QmsUserProblem::getUserId, userId)
                .orderByAsc(QmsUserProblem::getProblemNumber)
                .orderByDesc(QmsUserProblem::getGmtModified)
                .orderByDesc(QmsUserProblem::getGmtCreate)
        );
        /**
         * 答案数据
         */
        List<QmsUserProblemVo> problemVoList = list.stream().map(pojo -> {
            // 获取答案数据
            List<QmsUserAnswer> qmsAnswerList = qmsUserAnswerService.list(new LambdaQueryWrapper<QmsUserAnswer>().eq(QmsUserAnswer::getProblemId, pojo.getProblemId()));
            List<QmsUserAnswerVo> answerVoList = qmsAnswerList.stream().map(answer -> {
                QmsUserAnswerVo answerVo = new QmsUserAnswerVo();
                BeanUtil.copyProperties(answer, answerVo);
                return answerVo;
            }).collect(Collectors.toList());

            QmsUserProblemVo qmsUserProblemVo = new QmsUserProblemVo();
            BeanUtil.copyProperties(pojo, qmsUserProblemVo);
            qmsUserProblemVo.setQmsUserAnswerVoList(answerVoList);

            return qmsUserProblemVo;
        }).collect(Collectors.toList());

        BeanUtil.copyProperties(questionnaire, userQuestionnaireResultVo);
        userQuestionnaireResultVo.setUserProblemVoList(problemVoList);
        // 获取答案数据
        return userQuestionnaireResultVo;
    }


    @Override
    public QmsSubmitQuestionnaireResponseVo sendUserQuestionnaire(UserQuestionnaireForm form) {

        QmsSubmitQuestionnaireResponseVo qmsSubmitQuestionnaireVo = new QmsSubmitQuestionnaireResponseVo();


        // 获取userId
        Long userId = RequestUtils.getUserId();
//            AuditionJobInfo auditionJobInfo = auditionJobInfoService.getOne(new LambdaQueryWrapper<AuditionJobInfo>().eq(AuditionJobInfo::getUserId, userId));
//            if (Objects.equals(auditionJobInfo, null)){
//                throw new BizException("请提交完登记信息后，再进行测试");
//            }
        int userTotalScore = 0;
        // 获取通用配置项配置的压力测试的 主键ID
        Long questionnaireId = Long.valueOf(form.getAppQuestionnaireId());
        /*// 校验版本号
        QmsQuestionnaire qmsQuestionnaire = qmsQuestionnaireService.getById(questionnaireId);
        if (qmsQuestionnaire.getVersion() != Integer.parseInt(form.getVersion())) {
            return null;
        }*/
        log.info("UserAnswerFormList = {}", form.getUserAnswerFormList());

        // 获取问卷信息
        QmsQuestionnaire questionnaire = qmsQuestionnaireService.getById(questionnaireId);
        QmsUserQuestionnaire qmsUserQuestionnaire = new QmsUserQuestionnaire();

        BeanUtil.copyProperties(questionnaire, qmsUserQuestionnaire, "id");
        qmsUserQuestionnaire.setQuestionnaireId(questionnaireId);
        qmsUserQuestionnaire.setUserId(userId);
//            qmsUserQuestionnaire.setUserName(auditionJobInfo.getUserName());
//            qmsUserQuestionnaire.setUserJob(auditionJobInfo.getApplyToPosition());
        //设置版本号
        qmsUserQuestionnaire.setVersion(Integer.parseInt(form.getVersion()));
        //设置得分
        userTotalScore = returnScore(form, userTotalScore);
        qmsUserQuestionnaire.setUserTotalScore(userTotalScore);
        //设置评价
        qmsUserQuestionnaire.setEvaluationRecommend(evaluation(userTotalScore));
        boolean save = qmsUserQuestionnaireService.save(qmsUserQuestionnaire);

        // 获取试题数据
        //获取用户问卷ID
        Long userQuestionnaireId = questionnaire.getId();
        //存储用户试题
        form.getUserAnswerFormList().forEach(item -> {
            QmsUserProblem qmsUserProblem = new QmsUserProblem();
            QmsProblem qmsProblem = qmsProblemService.getOne(new LambdaQueryWrapper<QmsProblem>().eq(QmsProblem::getId, item.getProblemId()));
            BeanUtil.copyProperties(qmsProblem, qmsUserProblem, "id");
            qmsUserProblem.setProblemId(item.getProblemId());
            qmsUserProblem.setUserId(userId);
            qmsUserProblem.setUserQuestionnaireId(userQuestionnaireId);

            //获取答案数据
            List<QmsAnswer> qmsAnswerList = qmsAnswerService.list(new LambdaQueryWrapper<QmsAnswer>().eq(QmsAnswer::getProblemId, item.getProblemId()));
            qmsAnswerList.forEach(x -> {
                QmsUserAnswer qmsUserAnswer = new QmsUserAnswer();
                BeanUtil.copyProperties(x, qmsUserAnswer, "id");
                if (x.getId().equals(item.getAnswerId())) {
                    qmsUserAnswer.setSign(0);
                } else {
                    qmsUserAnswer.setSign(1);
                }
                //设置问题表ID
                qmsUserAnswer.setProblemId(item.getProblemId());
                //设置用户问题ID
                qmsUserAnswer.setUserProblemId(qmsUserProblem.getId());
                //设置用户ID
                qmsUserAnswer.setUserId(userId);
                //设置用户问卷表ID
                qmsUserAnswer.setUserQuestionnaireId(userQuestionnaireId);
                //设置答案表ID
                qmsUserAnswer.setAnswerId(x.getId());

                String answer = x.getAnswer();


                //保存用户答案信息
                boolean save1 = qmsUserAnswerService.save(qmsUserAnswer);
            });


        });

        /**
         * 判断答题正确或错误个数 及返回星星数量
         */
        List<ShowQuestionnaireResponseVo> list = new ArrayList<>();
        List<UserAnswerForm> userAnswerFormList = form.getUserAnswerFormList();
        Integer appQuestionnaireId = form.getAppQuestionnaireId();
        List<QmsProblem> qmsProblemList = qmsProblemService.list(new LambdaQueryWrapper<QmsProblem>().eq(QmsProblem::getQuestionnaireId, appQuestionnaireId));

        //ShowQuestionnaireVo showQuestionnaireVo = null;
        Double max = (double) userAnswerFormList.size();
        Double min = 0.0;

        for (UserAnswerForm userAnswerForm : userAnswerFormList) {
            ShowQuestionnaireResponseVo showQuestionnaireVo = new ShowQuestionnaireResponseVo();

            for (QmsProblem qmsProblem : qmsProblemList) {
                if (userAnswerForm.getProblemId().equals(qmsProblem.getId())) {
                    showQuestionnaireVo.setId(qmsProblem.getId());
                    showQuestionnaireVo.setTitle(qmsProblem.getProblem());
                    List<QmsAnswer> answerList = qmsAnswerService.list(new LambdaQueryWrapper<QmsAnswer>().eq(QmsAnswer::getProblemId, qmsProblem.getId()));
                    for (QmsAnswer qmsAnswer : answerList) {
                        if (qmsAnswer.getPoints().equals("1")) {
                            showQuestionnaireVo.setAnswerTitle(qmsAnswer.getAnswer());
                        }
                    }
                }
            }

            Long answerId = userAnswerForm.getAnswerId();
            QmsAnswer qmsAnswer = qmsAnswerService.getOne(new LambdaQueryWrapper<QmsAnswer>().eq(QmsAnswer::getId, answerId));
            if (qmsAnswer.getPoints().equals("1")) {
                showQuestionnaireVo.setRightOrWrong(1);
            } else {
                showQuestionnaireVo.setRightOrWrong(0);
                min=min+1;
            }

            list.add(showQuestionnaireVo);
        }

        List<QmsUserQuestionnaireState> qmsUserQuestionnaireStateList = qmsUserQuestionnaireStateService.list(
                new LambdaQueryWrapper<QmsUserQuestionnaireState>().eq(QmsUserQuestionnaireState::getUserId, RequestUtils.getUserId()));

        Integer points=0;

        /*
         * 星星数量
         * */
        if (((max - min) / max) * 10.0 <= 6.0) {
            qmsSubmitQuestionnaireVo.setStars(0);
            points=0;
            qmsSubmitQuestionnaireVo.setTotalScore(0);
        } else if (((max - min) / max) * 10.0 > 6.0 && ((max - min) / max) * 10.0 <= 8.0) {
            qmsSubmitQuestionnaireVo.setStars(1);
            points=(int) (questionnaire.getTotalScore()*0.6);
            qmsSubmitQuestionnaireVo.setTotalScore(2);
        } else if (((max - min) / max) * 10.0 > 8.0 && ((max - min) / max) * 10.0 < 10.0) {
            qmsSubmitQuestionnaireVo.setStars(2);
            points=(int) (questionnaire.getTotalScore()*0.8);
            qmsSubmitQuestionnaireVo.setTotalScore(4);
        } else if (((max - min) / max) * 10.0 == 10.0) {
            qmsSubmitQuestionnaireVo.setStars(3);
            points=questionnaire.getTotalScore();
            qmsSubmitQuestionnaireVo.setTotalScore(6);
        }

        /*
        分数判断
         */
        for (QmsUserQuestionnaireState qmsUserQuestionnaireState : qmsUserQuestionnaireStateList) {
            if(qmsUserQuestionnaireState.getUserQuestionnaireId().equals(form.getAppQuestionnaireId())){
                qmsSubmitQuestionnaireVo.setTotalScore(0);
                points=0;
                break;
            }
        }

        UmsMember umsMember = iUmsUserService.getOne(new LambdaQueryWrapper<UmsMember>().eq(UmsMember::getId,userId));
        Long point = umsMember.getPoint();
        point=point+Long.valueOf(points);
        umsMember.setPoint(point);
        iUmsUserService.updateById(umsMember);

        qmsSubmitQuestionnaireVo.setQuestionnaireId(form.getAppQuestionnaireId());
        qmsSubmitQuestionnaireVo.setShowQuestionnaireResponseVos(list);

        /**
         * 将结果添加到QmsUserQuestionnaireState表中
         */
        boolean remove = false;
        for (QmsUserQuestionnaireState qmsUserQuestionnaireState : qmsUserQuestionnaireStateList) {
            if (qmsUserQuestionnaireState.getUserQuestionnaireId().equals(userQuestionnaireId)) {
                remove = qmsUserQuestionnaireStateService.remove(new LambdaQueryWrapper<QmsUserQuestionnaireState>().eq(QmsUserQuestionnaireState::getUserQuestionnaireId, qmsUserQuestionnaireState.getUserQuestionnaireId()));
                break;
            }
        }

        QmsUserQuestionnaireState qmsUserQuestionnaireState = new QmsUserQuestionnaireState();
        qmsUserQuestionnaireState.setUserId(RequestUtils.getUserId());
        qmsUserQuestionnaireState.setUserQuestionnaireId(userQuestionnaireId);
        qmsUserQuestionnaireState.setUserTotalScore(qmsSubmitQuestionnaireVo.getStars());
        qmsUserQuestionnaireStateService.save(qmsUserQuestionnaireState);


        //保存用户答案信息
        return qmsSubmitQuestionnaireVo;
    }


    public int returnScore(UserQuestionnaireForm form, int userTotalScore) {
        List<UserAnswerForm> userAnswerFormList = form.getUserAnswerFormList();
        for (UserAnswerForm x : userAnswerFormList) {
            log.info("UserAnswerForm ={}", x);
            QmsAnswer answer = qmsAnswerService.getOne(new LambdaQueryWrapper<QmsAnswer>().eq(QmsAnswer::getId, x.getAnswerId()));
            log.info("answer={}", answer);
            if (answer != null) {
                if (answer.getPoints() == null) {
                    log.info(x.getProblemId() + "的答案的分值为空,无法计分");
                }
                userTotalScore = userTotalScore + Integer.parseInt(answer.getPoints());
            } else {
                log.info(x.getProblemId() + "的答案不存在,无法计分");
            }

        }
        return userTotalScore;
    }

    public String evaluation(int score) {
        if (score < 101 && score > 82) {
            return "被评测人的抗压能力非常强，勇于挑战，善于自我调整，遇到困难都能够积极应对";
        } else if (score < 83 && score > 65) {
            return "被评测人的抗压能力较强，除了事态严重时，多数情况都能从容应对";
        } else if (score < 66 && score > 47) {
            return "被评测人的抗压能力一般，面对压力偶尔会选择逃避";
        } else {
            return "被评测人的抗压能力较差，不愿意改变自我，遇到困难容易退缩";
        }
    }

}
